package cn.afactory.tygz.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import cn.afactory.tygz.db.DBManager;
import cn.afactory.tygz.model.MessageDetailList;
import cn.afactory.tygz.model.PrivateUserInfoList;
import cn.afactory.tygz.model.SysMessageItemList;
import cn.afactory.tygz.net.NetManager;
import cn.afactory.tygz.net.lsn.OnResponseListener;
import cn.afactory.tygz.ui.base.utils.HarwkinLogUtils;
import cn.afactory.tygz.ui.base.utils.SPUtils;

/**
 * Created with Android Studio.
 * Title:CoreService
 * Description:
 * Copyright:Copyright (c) 2014
 * Company:中国平安健康保险有限公司
 * Author:Alice
 * Date:15/8/24
 * Time:下午5:45
 * Version 1.0
 */
public class CoreService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        HarwkinLogUtils.getInstance().info("Harwkin","CoreService onCreate");
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(intent == null && intent.getAction() == null){
            return Service.START_STICKY;
        }
        String action = intent.getAction();
        if(SPUtils.ACTION_SYNC_MESSAGE_OK.equals(action)){
            doSyncThreads();
            doSyncSysMessages();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 后台同步私信列表
     */
    private void doSyncThreads(){
        NetManager.getInstance(this).doGetPrivateUserList(1, 1000, System.currentTimeMillis(), new OnResponseListener<PrivateUserInfoList>() {
            @Override
            public void onComplete(boolean isOK, PrivateUserInfoList result, int errorCode, String errorMsg) {
                if(isOK && result.value.size() > 0){
                    DBManager.getInstance(CoreService.this).updateThreads(result.value);
                    sendBroadcast(new Intent(SPUtils.BR_ACTION_SYNC_MESSAGE_OK));
                }
            }

            @Override
            public void onInternError(int errorCode, String errorMessage) {

            }
        });
    }

    /**
     * 同步系统消息
     */
    private void doSyncSysMessages(){
        NetManager.getInstance(this).doGetSysMsgList(1, 1000, System.currentTimeMillis(),
                new OnResponseListener<SysMessageItemList>() {
            @Override
            public void onComplete(boolean isOK, SysMessageItemList result, int errorCode, String errorMsg) {
                if(isOK && result.value.size() > 0){
                    DBManager.getInstance(CoreService.this).updateSysMessageList(result.value);
                }
            }

            @Override
            public void onInternError(int errorCode, String errorMessage) {

            }
        });
    }
}
